package com.littlebee.storychild.common.tcp;


import android.content.Context;
import android.content.Intent;
import android.view.View;

import com.littlebee.storychild.common.BaseApplication;
import com.littlebee.storychild.common.utils.GsonUtils;
import com.littlebee.storychild.common.utils.LogUtil;
import com.littlebee.storychild.common.utils.ToastUtil;
import com.littlebee.storychild.common.utils.Utils;
import com.littlebee.storychild.common.utils.sharePrefUtils.SharePrefUtil;
import com.littlebee.storychild.ui.StoryInfoImagePlayActivity;
import com.littlebee.storychild.ui.VoiceCallingActivity;
import com.littlebee.storychild.ui.entry.User;
import com.tjstudy.tcplib.RequestCallback;
import com.tjstudy.tcplib.ResponseCallback;
import com.tjstudy.tcplib.TCPClient;
import com.zss.library.widget.CommonWhiteDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.net.Socket;

/**
 * Created by liaoyong on 26/11/2017.
 */

public class TcpClientUtil {
    public static final int mPort = 11000;
    public static final String mIPAddress = "47.92.37.125";
    private TCPClient tcpClient;
    private static Context mContext;
    private static TcpClientUtil _instance=null;

    public static TcpClientUtil getInstance(Context context){
        if (_instance == null) {
            _instance = new TcpClientUtil();
        }
        mContext = context;
        return _instance;
    }

    public void init() {
        JSONObject heartJson = new JSONObject();
        try {
            heartJson.put("msgid", 5);
            heartJson.put("msgdesc", "app keep live");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        tcpClient = TCPClient.build()
                .server(mIPAddress, mPort)
                .breath(heartJson.toString().getBytes(), 30 * 1000)
                .connTimeout(10 * 1000);
    }

    public void sendMessage(SendCmdBean sendCmdBean) {
        if (tcpClient == null) {
            init();
        }

        String sendMess = GsonUtils.toJson(sendCmdBean);
        LogUtil.d("liaoyong: message"+sendMess);

        tcpClient.request(sendMess.getBytes(), mPort, new RequestCallback() {
            @Override
            public void onTimeout() {
                LogUtil.e("onTimeout:请求超时，稍后重试 ,关闭连接 ");
                TCPClient.closeTcp(mIPAddress, mPort);
            }

            @Override
            public void onFail(Throwable throwable) {
                handlerError(throwable);
            }
        }, responseCallback);
    }

    public void sendMessage(SendCmdBean sendCmdBean, ResponseCallback callback) {
        if (tcpClient == null) {
            init();
        }
        String sendMess = GsonUtils.toJson(sendCmdBean);
        LogUtil.d("liaoyong: message"+sendMess);

        tcpClient.request(sendMess.getBytes(), mPort, new RequestCallback() {
            @Override
            public void onTimeout() {
                LogUtil.e("onTimeout:请求超时，稍后重试 ,关闭连接 ");
                TCPClient.closeTcp(mIPAddress, mPort);
            }

            @Override
            public void onFail(Throwable throwable) {
                handlerError(throwable);
            }
        }, callback);
    }

    public void sendMessage(int msgid, ResponseCallback callback) {
        JSONObject heartJson = new JSONObject();
        try {
            heartJson.put("msgid", 5);
            heartJson.put("msgdesc", "app keep live");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        tcpClient = TCPClient.build()
                .server(mIPAddress, mPort)
                .breath(heartJson.toString().getBytes(), 30 * 1000)
                .connTimeout(10 * 1000);

        User user = Utils.getUserEntry();
        JSONObject sendjson = new JSONObject();
        try {
            if( msgid == 1) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "mother connect");
                sendjson.put("myid", user.getMobile());
            } else if (msgid == 2) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "baby connect");
                sendjson.put("myid", user.getMobile());
            } else if( msgid == 3) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "呼叫宝宝");
                sendjson.put("mamaid", user.getMobile());
                sendjson.put("babyid", user.getMobile());
            } else if( msgid == 4) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "同步故事给宝宝");
                sendjson.put("babyid", user.getMobile());
                sendjson.put("storyid", "1234");
                sendjson.put("pageno", "1");
            } else if( msgid == 5) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "app keep live");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String sendMess = sendjson.toString();
        LogUtil.d("liaoyong: message"+sendMess);

        tcpClient.request(sendMess.getBytes(), mPort, new RequestCallback() {
            @Override
            public void onTimeout() {
                LogUtil.e("onTimeout:请求超时，稍后重试 ,关闭连接 ");
                TCPClient.closeTcp(mIPAddress, mPort);
            }

            @Override
            public void onFail(Throwable throwable) {
                handlerError(throwable);
            }
        }, callback);
    }

    public void sendMessage(int msgid) {
        JSONObject heartJson = new JSONObject();
        try {
            heartJson.put("msgid", 5);
            heartJson.put("msgdesc", "app keep live");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        tcpClient = TCPClient.build()
                .server(mIPAddress, mPort)
                .breath(heartJson.toString().getBytes(), 30 * 1000)
                .connTimeout(10 * 1000);

        User user = Utils.getUserEntry();
        JSONObject sendjson = new JSONObject();
        try {
            if( msgid == 1) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "mother connect");
                sendjson.put("myid", user.getMobile());
            } else if (msgid == 2) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "baby connect");
                sendjson.put("myid", user.getMobile());
            } else if( msgid == 3) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "呼叫宝宝");
                sendjson.put("mamaid", user.getMobile());
                sendjson.put("babyid", user.getMobile());
            } else if( msgid == 4) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "同步故事给宝宝");
                sendjson.put("babyid", user.getMobile());
                sendjson.put("storyid", "1234");
                sendjson.put("pageno", "1");
            } else if( msgid == 5) {
                sendjson.put("msgid",msgid );
                sendjson.put("msgdesc", "app keep live");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String sendMess = sendjson.toString();
        LogUtil.d("liaoyong: message"+sendMess);

        tcpClient.request(sendMess.getBytes(), mPort, new RequestCallback() {
            @Override
            public void onTimeout() {
                LogUtil.e("onTimeout:请求超时，稍后重试 ,关闭连接 ");
                TCPClient.closeTcp(mIPAddress, mPort);
            }

            @Override
            public void onFail(Throwable throwable) {
                handlerError(throwable);
            }
        }, responseCallback);
    }

    private void handlerError(Throwable throwable) {
        LogUtil.e("handlerError: 网络访问失败:" + throwable.getMessage());
    }

    private ResponseCallback responseCallback = new ResponseCallback() {
        @Override
        public void onRec(Object recObject) {
            LogUtil.d("liaoyong:recv:" + recObject.toString());
            SendCmdBean sendCmdBean = GsonUtils.getObjFromJSON(recObject.toString(), SendCmdBean.class);
            if (sendCmdBean.msgid == SendCmdBean.CMD_CONNECT_BABY_TYPE) {
                final CommonWhiteDialog dialog = new CommonWhiteDialog(mContext);
                dialog.setTitle("提示");
                dialog.setContentText("妈妈呼叫你，赶紧通话吧");
                dialog.setDisplayMiddleEnable(true);
                dialog.setOnClickCancelListener("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.setOnClickConfirmListener("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        Intent intent = new Intent(BaseApplication.getInstance(), VoiceCallingActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        BaseApplication.getInstance().startActivity(intent);
                    }
                });
                dialog.show();
            } else if (sendCmdBean.msgid == SendCmdBean.CMD_SYNC_PAGE_TYPE) {
                ToastUtil.displayLongToast("recv sync page " + sendCmdBean.storyid);
                Intent intent = new Intent(BaseApplication.getInstance(), StoryInfoImagePlayActivity.class);
                intent.putExtra("storyId", sendCmdBean.storyid);
                intent.putExtra("page", sendCmdBean.pageno);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                BaseApplication.getInstance().startActivity(intent);
            }
        }

        @Override
        public void onFail(Throwable throwable) {
            handlerError(throwable);
        }
    };
}
